﻿using AiBLSmartEdu.Module.SafeResponse.Middleware.EncryptHelpers;
using FrameworkCore.DI;
using Microsoft.AspNetCore.Http;
using System.Text;

namespace AiBLSmartEdu.Module.SafeResponse.Middleware;

#nullable disable

public class RequestDataDecryptor: IScopedDependency
{
    private readonly AESProvider  _aesProvider;

    public RequestDataDecryptor(AESProvider aesProvider)
    {
        _aesProvider = aesProvider;
    }

    public  void DecryptUrlData(HttpContext context)
    {
        if (!_aesProvider.SecretSettings.Enabled) return;

        // 读取查询参数
        var queryParameters = context.Request.Query;

        var decryptText = queryParameters.FirstOrDefault().Key;

        //var parameters = _aesProvider.Decrypt(decryptText);
        var parameters = "a=1&b=2";
        // 修改查询参数
        var modifiedQuery = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(parameters);

        // 构造新的查询字符串
         var queryStringBuilder = new StringBuilder();
        foreach (var kvp in modifiedQuery)
        {
            queryStringBuilder.Append(Uri.EscapeDataString(kvp.Key));
            queryStringBuilder.Append("=");
            queryStringBuilder.Append(Uri.EscapeDataString(kvp.Value));
            queryStringBuilder.Append("&");
        }

        var modifiedQueryString = queryStringBuilder.ToString().TrimEnd('&');

        // 如果有修改后的查询字符串，则添加问号
        var newQuery = string.IsNullOrEmpty(modifiedQueryString) ? "" : "?" + modifiedQueryString;

        // 更新请求对象的 Path 和 QueryString
        context.Request.QueryString = new QueryString(newQuery);
    }

    public async Task DecryptBodyData(HttpContext context)
    {
        // 读取请求体数据
        var requestBody = context.Request.Body;

        // 读取请求体内容
        string requestBodyContent;
        using (var reader = new StreamReader(requestBody))
        {
            requestBodyContent = await reader.ReadToEndAsync();
        }

        // 更新请求体数据
        byte[] bytes = Encoding.UTF8.GetBytes(requestBodyContent);
        context.Request.Body = new MemoryStream(bytes);

        // 可选：重新设置 ContentLength，避免长度不一致的问题
        context.Request.ContentLength = bytes.Length;
    }
}
